package com.misc.tunewsreader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;

/**
 * Class that handles posting and replying
 */
public class WritePost extends Activity {
    String reply_to, reply_text;
    String sender;
    static String original_text;
    Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.write_post);

	context = this;

	final Bundle extras = getIntent().getExtras();
	EditText newsgroup = (EditText) findViewById(R.id.write_newsgroup);
	newsgroup.setText(extras.getString("newsgroup"));

	String reply_subj = "";

	// set sender and subject
	if (extras.getString("reply") == null) {
	    reply_to = "";
	    reply_text = "";
	} else {
	    reply_to = extras.getString("reply");
	    reply_text = extras.getString("reply_text");
	    String[] reply_lines = reply_text.split("\n");
	    reply_text = extras.getString("reply_header") + "\r\n";
	    for (int i = 0; i < reply_lines.length; i++) {
		if (reply_lines[i].endsWith("\r"))
		    reply_lines[i] = reply_lines[i].substring(0,
			    reply_lines[i].length() - 1);
		String quote_sign = "> ";
		if (reply_lines[i].startsWith(">"))
		    quote_sign = ">";
		// don't quote signature
		if (i + 1 < reply_lines.length
			&& NNTPPost.isSignatureStart(reply_lines[i + 1])
			&& reply_lines[i].trim().length() == 0)
		    break;
		if (NNTPPost.isSignatureStart(reply_lines[i]))
		    break;
		reply_text += quote_sign + reply_lines[i] + "\r\n";
	    }
	    reply_subj = extras.getString("reply_subject");
	    if (!reply_subj.startsWith(this.getString(R.string.reply)))
		reply_subj = this.getString(R.string.reply) + " " + reply_subj;

	    ((EditText) findViewById(R.id.write_subject)).setText(reply_subj);
	}

	// get username
	SharedPreferences prefs = PreferenceManager
		.getDefaultSharedPreferences(getApplicationContext());
	sender = NNTPClient.formatSender(
		prefs.getString("pref_username", "Anonymous"),
		prefs.getString("pref_mail", "an@nym.us"));

	// add signature
	String sig = prefs.getString("pref_signature", "");
	if (!sig.trim().equals("")) {
	    reply_text += "\r\n-- \r\n" + sig;
	}

	original_text = reply_text;
	((EditText) findViewById(R.id.write_text)).setText(reply_text);

	// hide other fields when writing answer
	((EditText) findViewById(R.id.write_text))
		.setOnFocusChangeListener(new OnFocusChangeListener() {
		    @Override
		    public void onFocusChange(View v, boolean hasFocus) {
			((EditText) findViewById(R.id.write_newsgroup))
				.setVisibility(hasFocus ? View.GONE
					: View.VISIBLE);
			((EditText) findViewById(R.id.write_subject))
				.setVisibility(hasFocus ? View.GONE
					: View.VISIBLE);
		    }
		});

	// configure actionbar
	ActionBar bar = (ActionBar) findViewById(R.id.actionbar);
	if (reply_to.equals(""))
	    bar.setTitle(this.getString(R.string.post_to) + " "
		    + extras.getString("newsgroup"));
	else
	    bar.setTitle(this.getString(R.string.reply_to) + " "
		    + extras.getString("reply_subject"));

	bar.addAction(new CancelAction(this, R.drawable.bar_delete));
	bar.addAction(new WriteAction(this, R.drawable.bar_send));
    }

    @Override
    public void onBackPressed() {
	// if the write field has focus, clear focus and focus the subject field
	// instead
	final EditText write_text = ((EditText) findViewById(R.id.write_text));
	if (write_text.hasFocus()) {
	    write_text.clearFocus();
	    ((EditText) findViewById(R.id.write_subject)).requestFocus();
	    return;
	}
	// otherwise ask the user if he really wants to abort
	if (write_text.getText().toString().length() > 0) {
	    askAbort();
	} else {
	    this.finish();
	}
    }

    private void askAbort() {
	Builder warn_dlg = new AlertDialog.Builder(context)
		.setTitle(context.getString(R.string.warning))
		.setMessage(context.getString(R.string.cancel_posting))
		.setNegativeButton(context.getString(R.string.no), null)
		.setPositiveButton(context.getString(R.string.yes),
			new OnClickListener() {
			    @Override
			    public void onClick(DialogInterface dialog,
				    int which) {
				finish();
			    }
			});
	warn_dlg.show();
    }

    public static class CancelAction extends AbstractAction {
	private Context mContext;

	public CancelAction(Context context, int drawable) {
	    super(drawable);
	    mContext = context;
	}

	@Override
	public void performAction(View view) {
	    ((WritePost) mContext).askAbort();
	}
    }

    public static class WriteAction extends AbstractAction {
	private Context mContext;

	public WriteAction(Context context, int drawable) {
	    super(drawable);
	    mContext = context;
	}

	@Override
	public void performAction(View view) {
	    final String newsgroup = ((EditText) ((Activity) mContext)
		    .findViewById(R.id.write_newsgroup)).getText().toString();
	    final String subject = NNTPClient
		    .encodeText(((EditText) ((Activity) mContext)
			    .findViewById(R.id.write_subject)).getText()
			    .toString());
	    final String text = ((EditText) ((Activity) mContext)
		    .findViewById(R.id.write_text)).getText().toString();

	    // text was not changed
	    if (text.equals(original_text)) {
		Toast.makeText(mContext,
			mContext.getString(R.string.text_mustbe_changed),
			Toast.LENGTH_SHORT).show();
		return;
	    }

	    // deactivate gui
	    ((EditText) ((Activity) mContext)
		    .findViewById(R.id.write_newsgroup)).setEnabled(false);
	    ((EditText) ((Activity) mContext).findViewById(R.id.write_subject))
		    .setEnabled(false);
	    ((EditText) ((Activity) mContext).findViewById(R.id.write_text))
		    .setEnabled(false);
	    // change action bar
	    ActionBar bar = (ActionBar) ((Activity) mContext)
		    .findViewById(R.id.actionbar);
	    bar.removeAllActions();
	    bar.setTitle(((Activity) mContext).getString(R.string.wait_posting));

	    Runnable post = new Runnable() {
		@Override
		public void run() {
		    String msg = "";
		    // normal post
		    if (((WritePost) mContext).reply_to.equals("")) {
			Log.d("NNTP", "Subject: " + subject);

			if (NNTPClient.postToNewsgroup(newsgroup, subject,
				((WritePost) mContext).sender, text)) {
			    msg = mContext.getString(R.string.message_posted);
			    ((WritePost) mContext).finish();
			} else {
			    msg = mContext.getString(R.string.failed_post);
			}
		    } else {
			// reply
			if (NNTPClient.postAnswer(newsgroup,
				((WritePost) mContext).reply_to, subject,
				((WritePost) mContext).sender, text)) {
			    msg = mContext.getString(R.string.reply_posted);
			    ((WritePost) mContext).finish();
			} else {
			    msg = mContext.getString(R.string.failed_reply);
			}
		    }
		    final String toast_msg = msg;
		    // display toast message on ui thread
		    ((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
			    Toast.makeText(mContext, toast_msg,
				    Toast.LENGTH_SHORT).show();
			}
		    });
		}
	    };
	    Thread thread = new Thread(null, post, "PostPost");
	    thread.start();
	}
    }

}
